package com.party.tool;



import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;




import com.party.domain.User;




public class CookieUtils {
	public static final String USER_COOKIE = "guilongman.cookie";
	
	public static void addCookie(HttpServletResponse response,User user) throws UnsupportedEncodingException
	{
		String email=user.getEmail();
		int id=user.getId();
		String name=URLEncoder.encode(user.getName(),"UTF-8");

	//	System.out.println("id:"+id+"   "+"email:   "+email+"     "+"name:     "+name);
		Cookie cookie = new Cookie(USER_COOKIE,id+":"
				+ email+":"+name);

		cookie.setMaxAge(60 * 60 * 24 * 1);// cookie保存一天
		response.addCookie(cookie); 

	}
	
	/**
	 * 
	 * 获取cookie，辨别用户，当参数s=id时，返回cookie中的id，s=email则返回email，s=name返回name
	 * 为了防止伪造cookie，cookie中的邮箱会和数据库邮箱不匹配，则返回error
	 * 在action中切记要判断getCookie返回的cookie是否为error
	 */
	public static String getCookie(HttpServletRequest request,String s){
		//接收cookie

		Cookie[] cookies = request.getCookies();
		String id = null;
		String email = null;
		String name = null;
		String state="error";
		if (cookies!=null) {
			for(Cookie cookie : cookies){
				if (cookie.getName().equals("guilongman.cookie")) {
					String value=cookie.getValue();
					
					if (!value.equals(null)){
						String[] split = value.split(":");
						System.out.println("value:  "+split.toString());
						id = split[0];
						email = split[1];
						name = split[2];						
					}
				}
			}
			if (s.equals("id")) {
				state=id;
			}else if (s.equals("email")) {
				state=email;
			}else if (s.equals("name")) {
				state=name;
			}
		}else {
				state="error";
			}

		return state;
	}

}